package com.exsun.ex1077.ui.activity.msg

import android.os.Bundle
import android.view.View
import androidx.core.view.isEmpty
import com.drake.brv.utils.bindingAdapter
import com.drake.brv.utils.linear
import com.drake.brv.utils.setup
import com.exsun.ex1077.R
import com.exsun.ex1077.databinding.ActivityMsgBinding
import com.exsun.ex1077.databinding.ListItemMsgBinding
import com.exsun.ex1077.network.entity.Msg
import com.exsun.ex1077.ui.popup.MsgPopup
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.binding.visible
import com.zhangping.fastjetpack.callback.SimpleXPopupCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.extend.base.parseState
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.impl.ConfirmPopupView
import kotlinx.android.synthetic.main.activity_msg.*
import kotlinx.android.synthetic.main.activity_msg.refreshLayout
import kotlinx.android.synthetic.main.activity_vehicle_list.*

/**
 * 描述：消息
 * 作者：ZhangPing
 * 创建时间：2022/8/9 11:24
 */
class MsgActivity : BaseActivity<MsgViewModel, ActivityMsgBinding>(){

    override fun title() = "消息通知"

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        super.initView(savedInstanceState)
        msgListView.linear().setup {
            addType<Msg>(R.layout.list_item_msg)
            onBind {
                val model = getModel<Msg>()
                val binding = getBinding<ListItemMsgBinding>()
                binding.checkBox.visible(model.selectMode)
                binding.radDot.visible(model.isRead == 0)
                binding.swipeLayout.closeRightMenu(false)
                binding.title.text = model.messSendDO?.title
                binding.time.text = model.messSendDO?.sendTime
                binding.content.text = model.messSendDO?.content
                binding.delete.setOnClickListener {
                    if (mViewModel.selectMode.get()) return@setOnClickListener
                    showConfirm("确定要删除当前消息吗？"){
                        mViewModel.removeMsg(getModel<Msg>().id ?: "").observe(this@MsgActivity){
                            msgListView.closeMenus()
                            MsgPopup.success(activity, "删除成功")
                            mutable.removeAt(modelPosition)
                            notifyItemRemoved(modelPosition)
                            checkActionIcon()
                        }
                    }
                }
            }
            onClick(R.id.itemRoot){
                val model = getModel<Msg>()
                mViewModel.loadDetail(model.id ?: "").observe(this@MsgActivity){
                    it?.let {
                        if (model.isRead == 0){
                            //更新为已读
                            model.isRead = 1
                            notifyItemChanged(modelPosition)
                        }
                        toActivityForResult<MsgDetailActivity>(Bundle().apply {
                            putSerializable("model", getModel<Msg>())
                        }){
                            if (it.resultCode == RESULT_OK){
                                MsgPopup.success(activity, "删除成功")
                                mutable.removeAt(modelPosition)
                                notifyItemRemoved(modelPosition)
                                checkActionIcon()
                            }
                        }
                    }
                }
            }
        }

        selectAll.setOnCheckedChangeListener { buttonView, isChecked ->
            msgListView.bindingAdapter.models?.forEach {
                it as Msg
                it.checked = isChecked
            }
            msgListView.bindingAdapter.notifyDataSetChanged()
        }
        deleteAll.setOnClickListener {
            val adapter = msgListView.bindingAdapter
            val checkedList = adapter.models?.filter { (it as Msg).checked } ?: emptyList()
            if (checkedList.isNullOrEmpty()){
                "请至少选择一条要删除的消息".showToast()
                return@setOnClickListener
            }
            XPopup.Builder(this)
                .setPopupCallback(object : SimpleXPopupCallback(){
                    override fun onCreated(popupView: BasePopupView) {
                        popupView as ConfirmPopupView
                        popupView.cancelTextView.setTextColor(R.color.color_9B9B9B.toColorRes())
                        popupView.confirmTextView.setTextColor(R.color.color_FF6A6A.toColorRes())
                    }
                })
                .asConfirm("", "确认将这${checkedList.size}条消息删除？", "我再想想", "删除", {
                    mViewModel.batchRemoveMsg(checkedList.joinToString(",") { (it as Msg).id ?: "" }).observe(this){
                        MsgPopup.success(activity, "删除成功")
                        checkedList.reversed().forEach {
                            val position = adapter.models!!.indexOf(it)
                            adapter.mutable.removeAt(position)
                            adapter.notifyItemRemoved(position)
                        }
                        checkActionIcon()
                    }
                }, null, false).show()
        }

        refreshLayout.onRefresh {
            mViewModel.selectMode.set(false)
            mViewModel.loadData(index)
        }.refresh()

        refreshLayout.onLoadMore {
            mViewModel.loadData(index)
        }
    }

    override fun onActionClick(view: View) {
        super.onActionClick(view)
        mViewModel.selectMode.reversal()
        if (mViewModel.selectMode.get()){
            //进入选择模式
            mViewModel.actionIcon.set(R.drawable.select_mode_back)
            msgListView.bindingAdapter.models?.forEach {
                it as Msg
                it.selectMode = true
                it.checked = false
            }
        }else{
            //进入普通模式
            mViewModel.actionIcon.set(R.drawable.select_mode)
            msgListView.bindingAdapter.models?.forEach {
                it as Msg
                it.selectMode = false
                it.checked = false
            }
            selectAll.isChecked = false
        }
        msgListView.bindingAdapter.notifyDataSetChanged()
    }

    private fun checkActionIcon(){
        if (msgListView == null || msgListView.bindingAdapter.models.isNullOrEmpty()){
            mViewModel.actionIcon.set(0)
            if (mViewModel.selectMode.get()){
                mViewModel.selectMode.set(false)
            }
        }else{
            mViewModel.actionIcon.set(R.drawable.select_mode)
        }
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listResult.observe(this){
            parseState(it, {
                val list = it?.rows ?: emptyList()
                refreshLayout.addData(list){ list.size >= mViewModel.pageSize }
                checkActionIcon()
            })
        }
    }

}